//
//  BottomView.m
//  StationManager
//
//  Created by 泽华伟业 on 17/3/6.
//  Copyright © 2017年 Helong. All rights reserved.
//

#import "BottomView.h"
#import "UIButton+typeLayout.h"
#import "BNRoutePlanModel.h"
#import "BNCoreServices.h"
#import "StationInfoModel.h"
#import "DataHandel.h"
#import "AlertDataView.h"
#import "MaintainViewController.h"
#import "EditView.h"
#import <MBProgressHUD.h>

@interface BottomView ()<BNNaviRoutePlanDelegate,BNNaviUIManagerDelegate,EditDelegate>

///站名lbael
@property (nonatomic,strong) UILabel *nameLabel;
///站号Label
@property (nonatomic,strong) UILabel *numberLabel;
///导航位置Label
@property (nonatomic,strong) UILabel *navigationLabel;
///位置Label
@property (nonatomic,strong) UILabel *locationLabel;
///经度Label
@property (nonatomic,strong) UILabel *longitudeLabel;
///纬度Label
@property (nonatomic,strong) UILabel *latitudeLabel;
///编辑Button
@property (nonatomic,strong) UIButton *editorButton;
///维护Button
@property (nonatomic,strong) UIButton *maintenanceButton;
///数据Button
@property (nonatomic,strong) UIButton *dataButton;
///导航Button
@property (nonatomic,strong) UIButton *navigationButton;
///model
@property (nonatomic,strong) StationInfoModel *stationInfoModel;
///弹出的半透明视图
@property (nonatomic,strong) UIView *backView;
@property (nonatomic,strong) UIView *backView2;
@property (nonatomic , strong) EditView *editView;
@property (strong,nonatomic) MBProgressHUD * hud;

@end

@implementation BottomView

- (instancetype)init
{
    self = [super init];
    if (self) {

        [self.maintenanceButton setTitle:@"维护" forState:UIControlStateNormal];
        [self.dataButton setTitle:@"数据" forState:UIControlStateNormal];
        [self.navigationButton setTitle:@"导航" forState:UIControlStateNormal];
        [self.editorButton setTitle:@"编辑" forState:UIControlStateNormal];

    }
    return self;
}

///站名
- (UILabel *)nameLabel{
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc]init];
        [_nameLabel setFont:[UIFont systemFontOfSize:12]];
        [self addSubview:_nameLabel];
        [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(10*wl);
            make.top.equalTo(self).offset(5*hl);
            make.size.mas_equalTo(CGSizeMake(150*wl, 20*hl));
        }];
        [_nameLabel sizeToFit];
    }
    return _nameLabel;
}

//站号Label
- (UILabel *)numberLabel{
    if (!_numberLabel) {
        _numberLabel = [[UILabel alloc]init];
        [_numberLabel setFont:[UIFont systemFontOfSize:12]];
        [self addSubview:_numberLabel];
        [_numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_nameLabel.mas_right).offset(10*wl);
            make.top.equalTo(_nameLabel);
            make.size.mas_equalTo(CGSizeMake(100*wl, 20*hl));
        }];
        [_numberLabel sizeToFit];
    }

    return _numberLabel;
}

///经度
- (UILabel *)longitudeLabel{
    if (!_longitudeLabel) {
        _longitudeLabel = [[UILabel alloc]init];
        [self addSubview:_longitudeLabel];
        [_longitudeLabel setFont:[UIFont systemFontOfSize:12]];
        [_longitudeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(10*wl);
            make.top.equalTo(_nameLabel.mas_bottom).offset(10*hl);
            make.size.mas_equalTo(CGSizeMake(150*wl, 20*hl));
        }];
        [_longitudeLabel sizeToFit];
    }
    return _longitudeLabel;
}

//纬度
- (UILabel *)latitudeLabel{
    if (!_latitudeLabel) {
        _latitudeLabel = [[UILabel alloc]init];
        [self addSubview:_latitudeLabel];
        [_latitudeLabel setFont:[UIFont systemFontOfSize:12]];
        [_latitudeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_longitudeLabel.mas_right).offset(10*wl);
            make.top.equalTo(_longitudeLabel);
            make.size.equalTo(_longitudeLabel);
        }];
        [_latitudeLabel sizeToFit];
    }
    return _latitudeLabel;
}
///导航位置
- (UILabel *)navigationLabel{
    if (!_navigationLabel) {
        _navigationLabel = [[UILabel alloc]init];
        [self addSubview:_navigationLabel];
        [_navigationLabel setFont:[UIFont systemFontOfSize:12]];
        [_navigationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_nameLabel);
            make.top.equalTo(_longitudeLabel.mas_bottom).offset(10*hl);
            make.right.equalTo(@-5);
            make.height.mas_equalTo(20);
        }];
        [_navigationLabel sizeToFit];
    }
    return _navigationLabel;
}

//位置Label
- (UILabel *)locationLabel{
    if (!_locationLabel) {
        _locationLabel = [[UILabel alloc]init];
        [self addSubview:_locationLabel];
        _locationLabel.numberOfLines = 0;
        [_locationLabel sizeToFit];
        [_locationLabel setFont:[UIFont systemFontOfSize:12]];
        [_locationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(10*wl);
            make.top.equalTo(_navigationLabel.mas_bottom).offset(10);
            make.right.equalTo(@-5);
            make.height.mas_equalTo(20);
        }];
    }
    return _locationLabel;
}

//维护按钮
- (UIButton *)maintenanceButton{
    if (!_maintenanceButton) {
        _maintenanceButton = [[UIButton alloc]init];
        [self setButtonMethodWithbutton:_maintenanceButton];
        [_maintenanceButton setImage:[UIImage imageNamed:@"weihu"] forState:UIControlStateNormal];
        [_maintenanceButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self);
            make.bottom.equalTo(self);
            make.height.mas_equalTo(50*hl);
            make.width.equalTo(self).dividedBy(4);
        }];
        [_maintenanceButton addTarget:self action:@selector(maintenanceButtonDidSelected:) forControlEvents:UIControlEventTouchUpInside];
        UIView *view = [[UIView alloc]init];
        view.backgroundColor = RGBCOLOR(120, 168, 203);
        [self addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_maintenanceButton.mas_top);
            make.left.right.equalTo(self);
            make.height.mas_equalTo(1);
        }];
    }
    return _maintenanceButton;
}

//数据按钮
- (UIButton *)dataButton{
    if (!_dataButton) {
        _dataButton = [[UIButton alloc]init];
        [self setButtonMethodWithbutton:_dataButton];
        [_dataButton setImage:[UIImage imageNamed:@"data"] forState:UIControlStateNormal];
        [_dataButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_maintenanceButton.mas_right);
            make.top.equalTo(_maintenanceButton);
            make.size.equalTo(_maintenanceButton);
        }];
        [_dataButton addTarget:self action:@selector(dataButtonDidSelected:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dataButton;
}

//导航按钮
- (UIButton *)navigationButton{
    if (!_navigationButton) {
        _navigationButton = [[UIButton alloc]init];
        [self setButtonMethodWithbutton:_navigationButton];
        [_navigationButton setImage:[UIImage imageNamed:@"nav"] forState:UIControlStateNormal];
        [_navigationButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_dataButton.mas_right);
            make.top.equalTo(_dataButton);
            make.size.equalTo(_dataButton);
        }];
        [_navigationButton addTarget:self action:@selector(navigationButtonDidSelected:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _navigationButton;
}
// 编辑按钮
- (UIButton *)editorButton{
    if (!_editorButton) {
        _editorButton = [[UIButton alloc]init];
        [self setButtonMethodWithbutton:_editorButton];
        [_editorButton setImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
//        [_editorButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.right.equalTo(self.mas_right).offset(-10*hl);
//            make.centerY.equalTo(self);
//            make.size.mas_equalTo(CGSizeMake(60*wl, 40*hl));
//        }];
        [_editorButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_navigationButton.mas_right);
            make.size.top.equalTo(_navigationButton);
        }];
        [_editorButton addTarget:self action:@selector(editorButtonDidSelected:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _editorButton;
}

///添加button相关放方法
- (void)setButtonMethodWithbutton:(UIButton *)button{
    [self addSubview:button];
//    if (button == _editorButton) {
//        [_editorButton layoutButtonWithEdgeInsetsStyle:HLButtonEdgeInsetsStyleRight imageTitleSpace:45*wl];
//    }else{
        [button layoutButtonWithEdgeInsetsStyle:HLButtonEdgeInsetsStyleLeft imageTitleSpace:10*wl];
//    }
    [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    button.backgroundColor = [UIColor clearColor];
    //设置点击高亮状态
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [button setBackgroundImage:[UIImage imageNamed:@"btn_backHight"] forState:UIControlStateHighlighted];
}

#pragma mark --给各个label赋值
- (void)setDataOnTheseLabelWithStationModel:(StationInfoModel *)stationModel{
    _stationInfoModel = stationModel;
    [self.nameLabel setText:[NSString stringWithFormat:@"站名：%@",stationModel.stationName]];
    [self.numberLabel setText:[NSString stringWithFormat:@"站号：%@",stationModel.stationNum]];
    [self.longitudeLabel setText:[NSString stringWithFormat:@"经度：%@",stationModel.longitude]];
    [self.latitudeLabel setText:[NSString stringWithFormat:@"纬度：%@",stationModel.latitude]];
    [self.navigationLabel setText:[NSString stringWithFormat:@"导航位置：%@",stationModel.navigationPosition]];
    [self.locationLabel setText:[NSString stringWithFormat:@"位置：%@",stationModel.position]];
}

#pragma mark -- button点击方法
///编辑点击
- (void)editorButtonDidSelected:(UIButton *)sender{
// 点击编辑按钮弹出界面编辑导航位置
    _backView2 = [[UIView alloc]init];
    [self.window addSubview:_backView2];
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backViewTap)];
    [_backView2 addGestureRecognizer:tapGR];
    _backView2.backgroundColor = RGBACOLOR(0, 0, 0, 0.5);
    [_backView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(self.window);
    }];

    _editView = [[EditView alloc] initWithFrame:CGRectMake(40, SCREEN_HEIGHT/6, SCREEN_WIDTH-80, 270)];
    _editView.editDelegate = self;
    _editView.stationNameLabel.text = [NSString stringWithFormat:@"站名：%@",_model.stationName];
    _editView.stationNumLabel.text = [NSString stringWithFormat:@"站号：%@",_model.stationNum];
    _editView.latitudeLabel.text = [NSString stringWithFormat:@"经度：%@",_model.longitude];
    _editView.longitudeLabel.text = [NSString stringWithFormat:@"纬度：%@",_model.latitude];
    _editView.locationLabel.text = [NSString stringWithFormat:@"位置：%@",_model.position];
    _editView.naviTF.text = _model.navigationPosition;
    [[UIApplication sharedApplication].keyWindow addSubview:_editView];
    
}

-(void)cancelButtonClick{
    [_editView removeFromSuperview];
    [_backView2 removeFromSuperview];
    
}


-(void)saveButtonClick{
    
    NSString *strPath=[NSString stringWithFormat:@"%@/Documents/taizhan",NSHomeDirectory()];
    NSArray *documentList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:strPath error:nil];
    for (NSInteger i=0; i<documentList.count; i++) {
        if ([documentList[i] hasPrefix:_model.stationName]) {
            [[NSFileManager defaultManager]  removeItemAtPath:[NSString stringWithFormat:@"%@/%@",strPath,documentList[i]] error:nil];
        }
    }
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString * dateTime = [formatter stringFromDate:date];
    
    NSString *strGeneralPath=[NSString stringWithFormat:@"%@/Documents/daohang",NSHomeDirectory()];
    [[NSFileManager defaultManager] createDirectoryAtPath:strGeneralPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSLog(@"%@",strGeneralPath);
    
    NSString *strFinalPath=[NSString stringWithFormat:@"%@/%@%@",strGeneralPath,_model.stationName,dateTime];
    [[NSFileManager defaultManager] createDirectoryAtPath:strFinalPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSLog(@"%@",strFinalPath);
    NSFileManager *fileManager =[NSFileManager defaultManager];

    NSString * filePath = [NSString stringWithFormat:@"%@/%@%@.txt",strFinalPath,self.model.stationName,dateTime];
    NSString *loadString = [NSString stringWithFormat:@"%@\r\n%@\r\n%@\r\n%@\r\n%@\r\n%@%@",_editView.stationNameLabel.text,_editView.stationNumLabel.text,_editView.latitudeLabel.text,_editView.longitudeLabel.text,_editView.locationLabel.text,_editView.naviLabel.text,_editView.naviTF.text];
    
    [fileManager createFileAtPath:filePath contents:[loadString dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

    [_editView removeFromSuperview];
    [_backView2 removeFromSuperview];
    [self showAlert:@"已保存台站信息" duration:1.0 IsSubmited:NO];
}

-(void)backViewTap{
    
    [_editView removeFromSuperview];
    [_backView2 removeFromSuperview];
}
///维护点击
- (void)maintenanceButtonDidSelected:(UIButton *)sender{
///跳转进入维护界面
    MaintainViewController *maintainVC = [[MaintainViewController alloc] init];
    maintainVC.stationModel = self.stationInfoModel;
    self.pushToWeihuBlock(self.stationInfoModel);
//    for (UIView* next = [self superview]; next; next = next.superview) {
//        UIResponder* nextResponder = [next nextResponder];
//        if ([nextResponder isKindOfClass:[UIViewController class]]) {
//            UIViewController *vc =  (UIViewController*)nextResponder;
//                [vc.navigationController pushViewController:maintainVC animated:YES];
//        }
//    }
    
}
///数据点击
- (void)dataButtonDidSelected:(UIButton *)sender{
//点击数据弹出气温、降水、风等信息，（最多三个都有，最少只有温度信息）
    _backView = [[UIView alloc]init];
    [self.window addSubview:_backView];
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backViewTapAction)];
    [_backView addGestureRecognizer:tapGR];
    _backView.backgroundColor = RGBACOLOR(0, 0, 0, 0.5);
    [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(self.window);
    }];
    if ([_stationInfoModel.stationType isEqualToString:@"T1"]) {
        //只有降水数据
        [self addAlertDataViewOnBackViewWithSegmentContrlNum:1];
    }else if ([_stationInfoModel.stationType isEqualToString:@"T2"] || [_stationInfoModel.stationType isEqualToString:@"G2"]  ){
       //有降水和气温两个
        [self addAlertDataViewOnBackViewWithSegmentContrlNum:2];
    }else if ([_stationInfoModel.stationType isEqualToString:@"T4"] || [_stationInfoModel.stationType isEqualToString:@"T6"]){
     //有降水、气温和风
        [self addAlertDataViewOnBackViewWithSegmentContrlNum:3];
    }
}
///导航点击
- (void)navigationButtonDidSelected:(UIButton *)sender{
///点击导航开始导航
    NSMutableArray *nodesArray = [[NSMutableArray alloc]initWithCapacity:2];
    //起点
    BNRoutePlanNode *startNode = [[BNRoutePlanNode alloc]init];
    startNode.pos = [[BNPosition alloc]init];
    startNode.pos.x = _location.coordinate.longitude;
    startNode.pos.y = _location.coordinate.latitude;
    startNode.pos.eType = BNCoordinate_BaiduMapSDK;
    [nodesArray addObject:startNode];
    //终点
    BNRoutePlanNode *endNode = [[BNRoutePlanNode alloc]init];
    endNode.pos = [[BNPosition alloc]init];
    endNode.pos.x = [_stationInfoModel.longitude floatValue];
    endNode.pos.y = [_stationInfoModel.latitude floatValue];
    endNode.pos.eType =  BNCoordinate_BaiduMapSDK;
    [nodesArray addObject:endNode];
    //发起路径规划
    [BNCoreServices_RoutePlan startNaviRoutePlan:BNRoutePlanMode_Recommend naviNodes:nodesArray time:nil delegete:self userInfo:nil];
    
}
#pragma mark -- 路线规划代理方法
//算路成功回调
- (void)routePlanDidFinished:(NSDictionary *)userInfo{
    //路径规划成功，开始导航
    [BNCoreServices_UI showPage:BNaviUI_NormalNavi delegate:self extParams:nil];
}

//算路失败回调
- (void)routePlanDidFailedWithError:(NSError *)error andUserInfo:(NSDictionary *)userInfo
{
    NSLog(@"算路失败");
    switch ([error code]%10000)
    {
        case BNAVI_ROUTEPLAN_ERROR_LOCATIONFAILED:
            NSLog(@"暂时无法获取您的位置,请稍后重试");
            break;
        case BNAVI_ROUTEPLAN_ERROR_ROUTEPLANFAILED:
            NSLog(@"无法发起导航");
            break;
        case BNAVI_ROUTEPLAN_ERROR_LOCATIONSERVICECLOSED:
            NSLog(@"定位服务未开启,请到系统设置中打开定位服务。");
            break;
        case BNAVI_ROUTEPLAN_ERROR_NODESTOONEAR:
            NSLog(@"起终点距离起终点太近");
            break;
        default:
            NSLog(@"算路失败");
            break;
    } }

//算路取消
-(void)routePlanDidUserCanceled:(NSDictionary*)userInfo {
    NSLog(@"算路取消");
}

#pragma mark -- 导航界面代理方法
//第一次进入导航页面会显示导航声明页，导航回调包括退出导航回调和退出导航声明页回调。
//退出导航页面回调
- (void)onExitPage:(BNaviUIType)pageType  extraInfo:(NSDictionary*)extraInfo
{
    if (pageType == BNaviUI_NormalNavi)
    {
        NSLog(@"退出导航");
    }
    else if (pageType == BNaviUI_Declaration)
    {
        NSLog(@"退出导航声明页面");
    }
}
//半透明视图手势
- (void)backViewTapAction{
    [_backView removeFromSuperview];
    AlertDataView *view = [self.window viewWithTag:170309];
    [view removeFromSuperview];
}

//添加弹出视图的方法
- (void)addAlertDataViewOnBackViewWithSegmentContrlNum:(int)num{
    //将站号有Bottom视图传到弹出的视图,并设置segmentControl有几个按钮
    AlertDataView *alertDataView = [[AlertDataView alloc]initWithElementNumber:num StationNum:_stationInfoModel.stationNum];
    [self.window addSubview:alertDataView];
    alertDataView.tag = 170309;
    [alertDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_backView);
        make.size.mas_equalTo(CGSizeMake(280*wl, 350*hl));
    }];
    
}


//弹出提示框
- (void)showAlert:(NSString *)message duration:(CGFloat)duration IsSubmited:(BOOL)isSubmited {
    
    _hud = [[MBProgressHUD alloc] init];
    _hud.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
    [[UIApplication sharedApplication].keyWindow addSubview:_hud];
    _hud.animationType =MBProgressHUDAnimationZoom;
    _hud.mode = MBProgressHUDModeText;
    _hud.label.text = message;
    _hud.label.numberOfLines = 0;
    _hud.label.font = [UIFont systemFontOfSize:12];
    _hud.removeFromSuperViewOnHide = YES;
    [_hud showAnimated:NO];
    [_hud hideAnimated:YES afterDelay:duration];
    
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
